<template>
  <div>
    <van-button type="primary" @click="showPopup">请选择分类</van-button>
    <van-popup position="bottom" v-model="show" :style="{ height: '70%' }">
      <div class="popup-content">
        <div class="tree-content" ref="treeContent">
          <van-radio-group v-model="selectedId" @change="onSelectChange">
            <tree-item v-for="item in items" :key="item.id" :item="item" :selected-id.sync="selectedId"></tree-item>
          </van-radio-group>
        </div>
        <div class="btns">
          <van-button type="default" @click="cancelPopup">取消</van-button>
          <van-button type="primary" @click="confirmSelection">确认</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import TreeItem from './TreeItem.vue';

export default {
  components: {
    TreeItem,
  },
  data() {
    return {
      show: false,
      items: [
        {
          text: "温州",
          id: 1,
          children: [
            {
              text: "3级",
              id: 11,
            },
          ],
        },
        {
          text: "杭州",
          id: 2,
        },
      ],
      selectedId: null,
      selectedItem: null,
    };
  },
  methods: {
    showPopup() {
      this.show = true;
    },
    cancelPopup() {
      this.show = false;
      this.selectedId = null;
      this.selectedItem = null;
    },
    confirmSelection() {
      if (this.selectedId !== null) {
        this.selectedItem = this.findItemById(this.items, this.selectedId);
        console.log('Selected Item:', this.selectedItem);
        this.show = false;
      }
    },
    findItemById(items, id) {
      for (const item of items) {
        if (item.id === id) {
          return item;
        }
        if (item.children) {
          const found = this.findItemById(item.children, id);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },
    onSelectChange(value) {
      this.selectedId = value;
    },
  },
};
</script>

<style scoped>
.popup-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.tree-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.btns {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border-top: 1px solid #ebedf0;
}
</style>